package com.sikong.calcite.csv;

import com.sikong.constant.StringSpliter;
import lombok.extern.slf4j.Slf4j;
import org.apache.calcite.linq4j.Enumerator;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * CSV文件迭代器Demo
 *
 * @param <T>
 * @author wangbohong
 * @Date 2022/02/26 16:26:22
 * @since 0.1.0
 */
@Slf4j
public class CsvEnumeratorDemo<T> implements Enumerator<T> {
    private T current;
    private BufferedReader br;

    public CsvEnumeratorDemo(FileReader reader) {
        try {
            br = new BufferedReader(reader);
            br.readLine();
        } catch (IOException e) {
            log.error("文件读写异常", e);
        }
    }

    @Override
    public T current() {
        return current;
    }

    /**
     * 重写方法：像下一行移动
     *
     * @return 下一行是否非空
     */
    @Override
    public boolean moveNext() {
        try {
            String line = br.readLine();
            if (line == null) {
                return false;
            }
            current = (T) line.split(StringSpliter.COMMA);
        } catch (IOException e) {
            log.error("指针移动失败", e);
            return false;
        }
        return true;
    }

    /**
     * Todo: 实际应用中，报错在这里处理
     */
    @Override
    public void reset() {
    }

    /**
     * Todo: 关闭InputStream流
     */
    @Override
    public void close() {
        try {
            br.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}
